﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.IO;
using System.Reflection;
using System.Data.OleDb;
using System.Drawing.Printing;

namespace GreetingCardApplication
{
    public partial class Form1 : Form
    {
        private int printStart = 0;
 
        public Form1()
        {
            InitializeComponent();
            this.printStart = 0;
            this.button2.Enabled = false;
           //string path = @"d:\test.xls";
           // DataSet ds = ExcelToDS(path);
           //loadData(ExcelToDS(path));
              
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.openFileDialog1.Filter = "*.xls|*.xls";
            this.openFileDialog1.FileName = "";
            if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string fileName = this.openFileDialog1.FileName;
                this.textBox1.Text = fileName;
                this.loadData(ExcelToDS(fileName)); ;
                this.printStart = 0;
                this.button2.Enabled = true;
            }
        }

        private void loadData(DataSet ds)
        {
            this.listView1.Items.Clear();
            this.listView1.BeginUpdate();

            DataTable dt = ds.Tables[0];
            foreach (DataRow dr in dt.Rows)
            {
                /**
                foreach (DataColumn dc in dt.Columns)
                {
                    //Console.WriteLine(@"{0},{1},{2}",ds.Tables[0].TableName,dc.ColumnName,row[dc]);
                    this.textBox1.Text += "," + dr[dc.ColumnName].ToString();
                }
                 */
                ListViewItem item = new ListViewItem(dr[dt.Columns[0].ColumnName].ToString());
                item.SubItems.Add(dr[dt.Columns[1].ColumnName].ToString());
                item.SubItems.Add(dr[dt.Columns[2].ColumnName].ToString());
                this.listView1.Items.Add(item);
            }     
            this.listView1.EndUpdate();
        }
     
        public DataSet ExcelToDS(string Path)
        {
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();
            string strExcel = "";
            OleDbDataAdapter myCommand = null;
            DataSet ds = null;
            strExcel = "select * from [sheet1$]";
            myCommand = new OleDbDataAdapter(strExcel, strConn);
            ds = new DataSet();
            myCommand.Fill(ds, "table1");
            return ds;
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.listView1.SelectedItems.Count > 0)
            {
                ListViewItem item = this.listView1.SelectedItems[0];
                string name = item.Text;
                string add = item.SubItems[1].Text;
                string post = item.SubItems[2].Text;
                this.label3.Text = "TO："+name;
                this.label4.Text = add;

                if (post.Length == 6)
                {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < post.Length; i++)
                    {
                        string c = post.Substring(i, 1);
                        sb.Append(c);
                        sb.Append(" ");
                        sb.Append(" ");
                    }
                    this.label2.Text = sb.ToString();
                }
                else 
                {
                    this.label2.Text = "";
                }
                
            }
            else
            {
                this.textBox1.Text = "";
            }
            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //打印
            Panel panel = this.panel1;
            bool isPrintView = this.checkBox1.Checked;
            //double pages = Math.Round(Convert.ToDouble(this.listView1.Items.Count / 2));
            //this.textBox1.Text =""+ pags;
            //for (int i = 0; i < this.listView1.Items.Count-1;i++ )
            //{
            //    System.Console.WriteLine("Page:"+(i+1));
            //PrintDocument类是实现打印功能的核心，它封装了打印有关的属性、事件、和方法
            PrintDocument printDocument = new PrintDocument();
            //设置纸张大小（可以不设置取，取默认设置）          
            PaperSize ps = new PaperSize("", 800, 1024);
            ps.RawKind = 9; //如果是自定义纸张，就要大于118，（A4值为9，详细纸张类型与值的对照请看http://msdn.microsoft.com/zh-tw/library/system.drawing.printing.papersize.rawkind(v=vs.85).aspx）
            printDocument.DefaultPageSettings.PaperSize = ps;
            printDocument.DefaultPageSettings.Landscape = true;
            printDocument.DefaultPageSettings.Color = true;
            
            PrintController printController = new StandardPrintController();
            printDocument.PrintController = printController;

            //打印开始前
            //printDocument.BeginPrint += new PrintEventHandler(printDocument_BeginPrint);
            //打印输出（过程）
            printDocument.PrintPage += new PrintPageEventHandler(printDocument_PrintPage);
            //打印结束
            //printDocument.EndPrint += new PrintEventHandler(printDocument_EndPrint);
            //printDocument.Print();

            //PrintDialog pd = new PrintDialog();
            //pd.Document = printDocument;
            //if (DialogResult.OK == pd.ShowDialog()) //如果确认，将会覆盖所有的打印参数设置
            //{
                //页面设置对话框（可以不使用，其实PrintDialog对话框已提供页面设置）
                //PageSetupDialog psd = new PageSetupDialog();
                //psd.Document = printDocument;
                //if (DialogResult.OK == psd.ShowDialog())
                //{
            if (isPrintView)
            {
                //打印预览
                PrintPreviewDialog ppd = new PrintPreviewDialog(); 
                
                ppd.Width = 1240;
                ppd.Height = 1754;
                ppd.Document = printDocument;
                if (DialogResult.OK == ppd.ShowDialog()) {
                    this.printStart = 0;
                    printDocument.Print(); //打印
                }
               // break;
            }
            else
            {
                printDocument.Print(); //打印
            }
            
                    //}
           // }
           
           //}
            this.printStart = 0;
        }

        private void printDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            if (this.printStart >= this.listView1.Items.Count - 1)
            {
                e.HasMorePages = false;
                this.printStart = this.listView1.Items.Count - 1;
            }
            else
            {
                e.HasMorePages = true;
            }
            //打印
            Panel panel = this.panel1;
            
            //Graphics g = panel.CreateGraphics();
            Graphics g = e.Graphics;
            //Brush b = new SolidBrush(Color.Black);
            Brush b = new SolidBrush(this.panel3.BackColor);

            Label lab1 = this.label2;
            Point p1 = lab1.Location;            
            //g.DrawString(lab.Text, lab.Font, b, new PointF(p.X, p.Y));

            Label lab2 = this.label3;
            Point p2 = lab2.Location;            
            //g.DrawString(lab.Text, lab.Font, b, new PointF(p.X, p.Y));

            Label lab3 = this.label4;
            Point p3 = lab3.Location;            
            //g.DrawString(lab.Text, lab.Font, b, new PointF(p.X, p.Y));

            Label lab4 = this.label5;
            Point p4 = lab4.Location;

            //g.DrawString(lab.Text, lab.Font, b, new PointF(p.X, p.Y));

            Label lab5 = this.label6;
            Point p5 = lab5.Location;

            //g.DrawString(lab.Text, lab.Font, b, new PointF(p.X, p.Y));

            Label lab6 = this.label7;
            Point p6 = lab6.Location;
            //g.DrawString(lab.Text, lab.Font, b, new PointF(p.X, p.Y));

            Label lab7 = this.label8;
            Point p7 = lab7.Location;
            //g.DrawString(lab.Text, lab.Font, b, new PointF(p.X, p.Y));

            int h = 10;
            int xx = 100;
            //foreach(ListViewItem item in this.listView1.Items)
            //for (int index = this.printStart; index < this.listView1.Items.Count; index++)
            //{
            ListViewItem item = this.listView1.Items[this.printStart];


            g.DrawRectangle(new Pen(Color.Red, 2), new Rectangle(new Point(10 + xx, 23 + h), new Size(30, 30)));
                g.FillRectangle(new SolidBrush(Color.White), new Rectangle(new Point(11, 24+h), new Size(28, 28)));

                g.DrawRectangle(new Pen(Color.Red, 2), new Rectangle(new Point(45 + xx, 23 + h), new Size(30, 30)));
                g.FillRectangle(new SolidBrush(Color.White), new Rectangle(new Point(46 + xx, 24 + h), new Size(28, 28)));

                g.DrawRectangle(new Pen(Color.Red, 2), new Rectangle(new Point(80 + xx, 23 + h), new Size(30, 30)));
                g.FillRectangle(new SolidBrush(Color.White), new Rectangle(new Point(81 + xx, 24 + h), new Size(28, 28)));

                g.DrawRectangle(new Pen(Color.Red, 2), new Rectangle(new Point(115 + xx, 23 + h), new Size(30, 30)));
                g.FillRectangle(new SolidBrush(Color.White), new Rectangle(new Point(116 + xx, 24 + h), new Size(28, 28)));

                g.DrawRectangle(new Pen(Color.Red, 2), new Rectangle(new Point(150 + xx, 23 + h), new Size(30, 30)));
                g.FillRectangle(new SolidBrush(Color.White), new Rectangle(new Point(151 + xx, 24 + h), new Size(28, 28)));

                g.DrawRectangle(new Pen(Color.Red, 2), new Rectangle(new Point(185 + xx, 23 + h), new Size(30, 30)));
                g.FillRectangle(new SolidBrush(Color.White), new Rectangle(new Point(186 + xx, 24 + h), new Size(28, 28)));

                string post = item.SubItems[2].Text;
                if ("".Equals(post) || post.Length != 6)
                {
                }
                else
                {
                    g.DrawString(post.Substring(0, 1), lab1.Font, b, new PointF(15 + xx, 30 + h));
                    g.DrawString(post.Substring(1, 1), lab1.Font, b, new PointF(50 + xx, 30 + h));
                    g.DrawString(post.Substring(2, 1), lab1.Font, b, new PointF(85 + xx, 30 + h));
                    g.DrawString(post.Substring(3, 1), lab1.Font, b, new PointF(120 + xx, 30 + h));
                    g.DrawString(post.Substring(4, 1), lab1.Font, b, new PointF(155 + xx, 30 + h));
                    g.DrawString(post.Substring(5, 1), lab1.Font, b, new PointF(190 + xx, 30 + h));
                }

                g.DrawString("TO：" + item.SubItems[0].Text, lab2.Font, b, new PointF(p2.X + xx, p2.Y + h));
                g.DrawString(item.SubItems[1].Text, lab3.Font, b, new PointF(p3.X + xx, p3.Y + h));
                g.DrawString(lab4.Text, lab4.Font, b, new PointF(p4.X + xx, p4.Y + h));
                g.DrawString(lab5.Text, lab5.Font, b, new PointF(p5.X + xx, p5.Y + h));
                g.DrawString(lab6.Text, lab6.Font, b, new PointF(p6.X + xx, p6.Y + h));
                g.DrawString(lab7.Text, lab7.Font, b, new PointF(p7.X + xx, p7.Y + h));
           //     h += 1000;
           // }
            this.printStart++;
            //e.Cancel//获取或设置是否取消打印
            //e.HasMorePages //为true时，该函数执行完毕后还会重新执行一遍（可用于动态分页）
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (DialogResult.OK == this.colorDialog1.ShowDialog())
            {
               this.panel2.BackColor = this.colorDialog1.Color;
               this.panel1.BackColor = this.colorDialog1.Color;
            }
            else
            { 
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (DialogResult.OK == this.colorDialog1.ShowDialog())
            {
                this.label2.ForeColor = this.colorDialog1.Color;
                this.label3.ForeColor = this.colorDialog1.Color;
                this.label4.ForeColor = this.colorDialog1.Color;
                this.label5.ForeColor = this.colorDialog1.Color;
                this.label6.ForeColor = this.colorDialog1.Color;
                this.label7.ForeColor = this.colorDialog1.Color;
                this.label8.ForeColor = this.colorDialog1.Color;
                this.panel3.BackColor = this.colorDialog1.Color;
            }
            else
            {
            }
        }

    }
}
